package com.platform.modules.cpt.service.impl;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.util.WebUtils;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.platform.common.exception.BusinessException;
import com.platform.common.utils.DownloadUtils;
import com.platform.common.utils.UUID;
import com.platform.dao.AttachmentDao;
import com.platform.entity.Attachment;
import com.platform.modules.cpt.dao.CptAcceptanceSuperviseReportStampDao;
import com.platform.modules.cpt.entity.CptAcceptanceEntity;
import com.platform.modules.cpt.entity.CptAcceptanceSuperviseReportEntity;
import com.platform.modules.cpt.entity.CptAcceptanceSuperviseReportStampEntity;
import com.platform.modules.cpt.entity.CptAcceptanceSuperviseTeamEntity;
import com.platform.modules.cpt.entity.CptAcceptanceTeamEntity;
import com.platform.modules.cpt.service.CptAcceptanceService;
import com.platform.modules.cpt.service.CptAcceptanceSuperviseReportService;
import com.platform.modules.cpt.service.CptAcceptanceSuperviseReportStampService;
import com.platform.modules.cpt.service.CptAcceptanceSuperviseTeamService;
import com.platform.modules.prj.entity.PrjProjectEntity;
import com.platform.modules.prj.service.PrjProjectService;
import com.platform.util.DocUtil;

@Service
public class CptAcceptanceSuperviseReportStampServiceImpl extends ServiceImpl<CptAcceptanceSuperviseReportStampDao, CptAcceptanceSuperviseReportStampEntity> implements CptAcceptanceSuperviseReportStampService {

    private static final Logger logger = LoggerFactory.getLogger(CptAcceptanceSuperviseReportStampServiceImpl.class);
    @Autowired
    private CptAcceptanceService cptAcceptanceService;
    @Autowired
    private CptAcceptanceSuperviseReportService cptAcceptanceSuperviseReportService;
    @Autowired
    private CptAcceptanceSuperviseTeamService cptAcceptanceSuperviseTeamService;
    @Autowired
    private DocUtil docUtil;
    @Autowired
    private AttachmentDao attachmentDao;
    @Autowired
    private PrjProjectService prjProjectService;
    
	@Override
	public CptAcceptanceSuperviseReportStampEntity queryOne(Map<String, Object> params) {
        params.put("sidx", "CREATE_TIME");
        params.put("asc", false);
        List<CptAcceptanceSuperviseReportStampEntity> list = baseMapper.selectList(params);
        if(list==null || list.isEmpty()){
            return null;
        }else{
            return list.get(0);
        }
	}


	@Override
	public Map<String, Object> createGczljdbg1File(CptAcceptanceEntity cptAcceptanceEntity, String newFileName) {
		Map<String, Object> result = new HashMap<>();
		
		CptAcceptanceEntity cptAcceptance = cptAcceptanceService.getById(cptAcceptanceEntity.getId());
		if(null==cptAcceptance) {
			throw new BusinessException("未找到工程竣工验收监督申请记录");
		}
		
		Map<String, Object> m = new HashMap<String, Object>();
		m.put("cptId", cptAcceptanceEntity.getId());
		CptAcceptanceSuperviseReportStampEntity cptAcceptanceSuperviseReportStampEntity = queryOne(m);
		if(null==cptAcceptanceSuperviseReportStampEntity || null==cptAcceptanceSuperviseReportStampEntity.getId()) {
			throw new BusinessException("未找到工程质量监督报告盖章记录");
		}
		
		CptAcceptanceSuperviseReportEntity cptAcceptanceSuperviseReport = cptAcceptanceSuperviseReportService.queryOne(m);
		if(null==cptAcceptanceSuperviseReport || null==cptAcceptanceSuperviseReport.getId()) {
			throw new BusinessException("未找到工程质量监督报告记录");
		}
		
		PrjProjectEntity prjProject = prjProjectService.getById(cptAcceptance.getPrjId());
		if(null==prjProject) {
			throw new BusinessException("未找到工程信息");
		}

		Map<String, Object> m2 = new HashMap<String, Object>();
		m2.put("cptId", cptAcceptanceEntity.getId());
		List<CptAcceptanceSuperviseTeamEntity> superviseTeamList = cptAcceptanceSuperviseTeamService.queryList(m2);
		if(null==superviseTeamList || superviseTeamList.size()<1) {
			throw new BusinessException("未找到工程质量监督人员");
		}
		

		List<Attachment> list = docUtil.getAttListByAttBusinessIdAndAttCode(cptAcceptanceEntity.getId(),"CPT_ACCPTANCE_FILES_GCZLJDBG1");
		//生成过签字文件, 且不重新签, 直接返回
		if(list.size()>0 && 1!=cptAcceptanceEntity.getReSign()){
			Attachment attachment = list.get(0);
	        result.put("fileName",attachment.getName());
	        result.put("attId",attachment.getId());
			return result;
		}
		//生成过签字文件, 且重新签, 删除已生成文件
		else if(list.size()>0 && 1==cptAcceptanceEntity.getReSign()) {
			if(null!=list && list.size()>0) {
				for(int i=0; i<list.size(); i++) {
					Attachment attachment = list.get(i);
					docUtil.deleteAtts(Arrays.asList(attachment.getId().split(",")));
				}
			}
		}
		
        //没生成过文件  或  重新生成文件
        String strDateFormat = "yyyy-MM-dd";
        SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
        
        //竣工验收 合格时间
        Calendar cal=Calendar.getInstance();
        cal.setTime(cptAcceptanceSuperviseReport.getQualifiedDate());
        int year = cal.get(Calendar.YEAR);//获取年份
        int month=cal.get(Calendar.MONTH);//获取月份
        int day=cal.get(Calendar.DATE);//获取日

        cal.setTime(cptAcceptanceSuperviseReport.getSuperviseStartDate());
        int year2 = cal.get(Calendar.YEAR);//获取年份
        int month2 =cal.get(Calendar.MONTH);//获取月份
        int day2 =cal.get(Calendar.DATE);//获取日
        
        cal.setTime(cptAcceptanceSuperviseReport.getSuperviseEndDate());
        int year3 = cal.get(Calendar.YEAR);//获取年份
        int month3 =cal.get(Calendar.MONTH);//获取月份
        int day3 =cal.get(Calendar.DATE);//获取日
        
        cal.setTime(cptAcceptanceSuperviseReport.getAuditDate());
        int year4 = cal.get(Calendar.YEAR);//获取年份
        int month4 =cal.get(Calendar.MONTH);//获取月份
        int day4 =cal.get(Calendar.DATE);//获取日
        
        cal.setTime(cptAcceptanceSuperviseReportStampEntity.getAuditDate());
        int year5 = cal.get(Calendar.YEAR);//获取年份
        int month5 =cal.get(Calendar.MONTH);//获取月份
        int day5 =cal.get(Calendar.DATE);//获取日
        
        
        
        Map<String, Object> ag11 = new HashMap<String, Object>();
        ag11.put("orgName", StringUtils.isNotBlank(prjProject.getBuildCorpName())?prjProject.getBuildCorpName():"");
        ag11.put("comartiperson", StringUtils.isNotBlank(prjProject.getBuildComartiperson())?prjProject.getBuildComartiperson():"");
        
        Map<String, Object> ag12 = new HashMap<String, Object>();
        ag12.put("orgName", StringUtils.isNotBlank(prjProject.getSgCorpName())?prjProject.getSgCorpName():"");
        ag12.put("comartiperson", StringUtils.isNotBlank(prjProject.getSgComartiperson())?prjProject.getSgComartiperson():"");
        
        Map<String, Object> ag13 = new HashMap<String, Object>();
        ag13.put("orgName", StringUtils.isNotBlank(prjProject.getJlCorpName())?prjProject.getJlCorpName():"");
        ag13.put("comartiperson", StringUtils.isNotBlank(prjProject.getJlComartiperson())?prjProject.getJlComartiperson():"");
        
        Map<String, Object> ag14 = new HashMap<String, Object>();
        ag14.put("orgName", "勘察单位");
        ag14.put("comartiperson", "勘察单位法人");
        
        Map<String, Object> ag15 = new HashMap<String, Object>();
        ag15.put("orgName", StringUtils.isNotBlank(prjProject.getSjCorpName())?prjProject.getSjCorpName():"");
        ag15.put("comartiperson", StringUtils.isNotBlank(prjProject.getSjComartiperson())?prjProject.getSjComartiperson():"");
        
        Map<String, Object> ag16 = new HashMap<String, Object>();
        ag16.put("orgName", "检测单位");
        ag16.put("comartiperson", "检测单位法人");
        
        Map<String, Object> ag17 = new HashMap<String, Object>();
        ag17.put("orgName", StringUtils.isNotBlank(prjProject.getStCorpName())?prjProject.getStCorpName():"");
        ag17.put("comartiperson", StringUtils.isNotBlank(prjProject.getStComartiperson())?prjProject.getStComartiperson():"");
        
        Map<String, Object> ag18 = new HashMap<String, Object>();
        ag18.put("orgName", "预拌混凝土企业");
        ag18.put("comartiperson", "预拌混凝土企业法人");
        
        //组装参数
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("ag1", prjProject.getPrjName());
		data.put("ag2", cptAcceptance.getUnitPrjName());
		data.put("ag3", prjProject.getAddress());
		data.put("ag4", prjProject.getJglx());
		data.put("ag5", prjProject.getGcms());
		data.put("ag6", prjProject.getPrjQuality());
		data.put("ag7", prjProject.getGcsgxkzh());
		data.put("ag8", year);
		data.put("ag9", month+1);
		data.put("ag10", day);
		data.put("ag11", ag11);
		data.put("ag12", ag12);
		data.put("ag13", ag13);
		data.put("ag14", ag14);
		data.put("ag15", ag15);
		data.put("ag16", ag16);
		data.put("ag17", ag17);
		data.put("ag18", ag18);
		data.put("ag19", cptAcceptanceSuperviseReport.getCcqk());
		data.put("ag20", cptAcceptanceSuperviseReport.getJdqk());
		data.put("ag21", cptAcceptanceSuperviseReport.getQkbz());
		data.put("ag22", superviseTeamList);
		data.put("ag23", year2);
		data.put("ag24", month2+1);
		data.put("ag25", day2);
		data.put("ag26", year3);
		data.put("ag27", month3+1);
		data.put("ag28", day3);
		data.put("ag29", cptAcceptanceSuperviseReport.getAuditOpinion());
		data.put("ag30", year4);
		data.put("ag31", month4+1);
		data.put("ag32", day4);
		data.put("ag33", cptAcceptanceSuperviseReportStampEntity.getAuditOpinion());
		data.put("ag34", year5);
		data.put("ag35", month5+1);
		data.put("ag36", day5);
		//替换null值
		processMap(data);

		
		//导出PDF
		String ftlFile = "jgys/gczljdbg1.xml";
		String fileName = DownloadUtils.exportPDF(data, ftlFile);
		
		//转换文件对象类型
        FileItem fileItem = createFileItem(fileName + ".pdf", newFileName);
        MultipartFile mfile = new CommonsMultipartFile(fileItem);
        
        //上传文件
        String attId = docUtil.createAtt(mfile, "CPT_ACCPTANCE_FILES_GCZLJDBG1", cptAcceptanceEntity.getId());
		
	    result.put("fileName",fileName);
	    result.put("attId",attId);
		return result;
	}


	@Override
	public void downloadGczljdbgFile(String cptId, HttpServletRequest request, HttpServletResponse response, String attCode) {
		List<Attachment> attList = docUtil.getAttListByAttBusinessIdAndAttCode(cptId, attCode);
		if(null==attList || attList.size()<1) {
			throw new BusinessException("未找到工程质量监督报告文件");
		}
		String attId = null;
		for(int i=0; i<attList.size(); i++) {
			Attachment attachment = attList.get(i);
			attachment.getName();
			attId = attachment.getId();
		}
		
		
		InputStream is = docUtil.getFile(attId);
    	
		// 实现文件下载
       byte[] buffer = new byte[1024];
       BufferedInputStream bis = null;
       try {
           bis = new BufferedInputStream(is);
           OutputStream os = response.getOutputStream();
           int i = bis.read(buffer);
           while (i != -1) {
               os.write(buffer, 0, i);
               i = bis.read(buffer);
           }
       }
       catch (Exception e) {
           
       }
       finally {
           if (bis != null) {
               try {
                   bis.close();
               } catch (IOException e) {
                   e.printStackTrace();
               }
           }
           if (is != null) {
               try {
               	is.close();
               } catch (IOException e) {
                   e.printStackTrace();
               }
           }
       }
		
	}

	@Override
	public void signGczljdbgFile(HttpServletRequest request, String cptId, String attCode, String FileName) {
		
		Map<String, Object> m = new HashMap<String, Object>();
		m.put("cptId", cptId);
		CptAcceptanceSuperviseReportStampEntity cptAcceptanceSupervise = queryOne(m);
		if(null==cptAcceptanceSupervise || null==cptAcceptanceSupervise.getId()) {
			throw new BusinessException("未找到工程质量监督报告记录");
		}
		
		//查询并删除所有 工程竣工验收监督记录一
		List<Attachment> list = docUtil.getAttListByAttBusinessIdAndAttCode(cptId,attCode);
		if(null!=list && list.size()>0) {
			for(int i=0; i<list.size(); i++) {
				Attachment attachment = list.get(i);
				docUtil.deleteAtts(Arrays.asList(attachment.getId().split(",")));
			}
		}
		
    	
        MultipartHttpServletRequest multipartRequest = WebUtils.getNativeRequest(request, MultipartHttpServletRequest.class);
        Map<String, MultipartFile> map = multipartRequest.getFileMap();
        MultipartFile attach = (MultipartFile) map.values().toArray()[0];
        InputStream inputStream = null;
        try {
            inputStream = attach.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String attId2 = UUID.getId();
        docUtil.createAtt(attId2, null, null, attCode, cptId, FileName, inputStream);
        
        baseMapper.updateById(cptAcceptanceSupervise);
	}
    


	//获取FileItem对象：
	private FileItem createFileItem(String filePath, String newFileName) {
	    FileItemFactory factory = new DiskFileItemFactory(16, null);
	    String textFieldName = "textField";
	    int num = filePath.lastIndexOf(".");
	    String extFile = filePath.substring(num);
	    FileItem item = factory.createItem(textFieldName, "text/plain", true, "MyFileName");
	    File newfile = new File(filePath);
	    int bytesRead = 0;
	    byte[] buffer = new byte[8192];
	    try {
	        FileInputStream fis = new FileInputStream(newfile);
	        OutputStream os = item.getOutputStream();
	        while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
	            os.write(buffer, 0, bytesRead);
	        }
	        os.close();
	        fis.close();
	    } catch (IOException e) {
	        e.printStackTrace();
	    }
	    return item;
	}

	@Override
	public void downloadSignGczljdbgFile(String cptId, HttpServletRequest request, HttpServletResponse response,
			String attCode) {

		List<Attachment> attList = docUtil.getAttListByAttBusinessIdAndAttCode(cptId, attCode);
		if(null==attList || attList.size()<1) {
			throw new BusinessException("未找到工程质量监督报告文件");
		}
		String attId = null;
		for(int i=0; i<attList.size(); i++) {
			Attachment attachment = attList.get(i);
			attachment.getName();
			attId = attachment.getId();
		}
		InputStream is = docUtil.getFile(attId);
    	Attachment attachment = attachmentDao.selectById(attId);
    	
    	//实现文件下载
		byte[] buffer = new byte[1024];
		BufferedInputStream bis = null;
		try {
			response.setHeader("content-type", "application/octet-stream");
			response.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(attachment.getName(), "UTF-8"));
			response.setContentType("application/octet-stream");

			bis = new BufferedInputStream(is);
			OutputStream os = response.getOutputStream();
			int i = bis.read(buffer);
			while (i != -1) {
				os.write(buffer, 0, i);
				i = bis.read(buffer);
			}
		}
		catch (Exception e) {
			e.printStackTrace();
		}finally {
			if (bis != null) {
				try {
					bis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	private void processMap(Map<String,Object> map) {
		//遍历map 
		for(Map.Entry<String, Object> entry : map.entrySet()) {
			//替换Null值, 防止生成doc文件时报错
            if(map.get(entry.getKey())==null) {
            	map.put(entry.getKey(), "");
            }
		}
	}
}
